<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU 名称">
        {{ spuInfo.spuName }}
      </el-form-item>
      <el-form-item label="SKU 名称">
        <el-input v-model="skuInfo.skuName" placeholder="SKU 名称"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input v-model="skuInfo.price" min="0" type="number" placeholder="价格"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input v-model="skuInfo.weight" min="0" type="number"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input v-model="skuInfo.skuDesc" type="textarea" placeholder="规格描述"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form-item v-for="(skuAttr, index) in attrInfoList" :key="skuAttr.id" :label="skuAttr.attrName"
          label-width="90px" style="margin-bottom: 10px">
          <el-select v-model="skuInfo.skuAttrValueList[index]" placeholder="请选择">
            <el-option v-for="skuAttrValue in skuAttr.attrValueList" :key="skuAttrValue.id"
              :value="(skuAttrValue.attrId + ':' + skuAttrValue.id)" :label="skuAttrValue.valueName"></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form-item v-for="(skuSaleAttr, index) in spuSaleAttrList" :label="skuSaleAttr.saleAttrName"
          label-width="100px" :key="skuSaleAttr.id" style="margin-bottom: 10px">
          <el-select v-model="skuInfo.skuSaleAttrValueList[index]" placeholder="请选择">
            <el-option v-for="spuSaleAttrValue in skuSaleAttr.spuSaleAttrValueList" :key="spuSaleAttrValue.id"
              :value="spuSaleAttrValue.id || ''" :label="spuSaleAttrValue.saleAttrValueName"></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table @select="handleSelect" @select-all="handleSelect" :data="spuImageList" border style="width: 100%">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column v-slot="{ row }" label="图片" width="180">
            <img :src="row.imgUrl" />
          </el-table-column>
          <el-table-column prop="imgName" label="名称"></el-table-column>
          <el-table-column v-slot="{ row }" label="操作">
            <el-button @click="handleSetDefault(row)" v-if="row.isDefault == '0'"
              :disabled="!skuInfo.skuImageList.find(item => item.spuImgId == row.id)" type="primary"
              size="small">设置默认</el-button>
            <el-tag v-else type="success"> 默认 </el-tag>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSave" type="primary">保存</el-button>
        <el-button @click="$emit('changeTab', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
export default {
  name: 'SkuForm'
}
</script>
<script setup lang="ts">
import { onMounted, ref, reactive, watch } from 'vue'
import { Plus, Edit, InfoFilled, Delete } from '@element-plus/icons-vue'
import type { spuListModel, spuItemModel, spuImageModel, spuImageListModel, spuSaleAttrListModel } from '@/api/product/model/spu'
import type { attrListModel } from '@/api/product/model/attr'
import type {
  skuInfoModel, skuImageModel, skuImageListModel, skuSaleAttrValueModel, skuSaleAttrValueListModel, skuAttrValueModel, skuAttrValueListModel
} from '@/api/product/model/sku'

import { reqGetAttrInfoList } from '@/api/product/attr'
import { reqGetSpuImageList, reqGetSpuSaleAttrList, } from '@/api/product/spu'
import { reqSaveSkuInfo } from '@/api/product/sku'
import { useCategoryStore } from '@/stores/category'

const props = defineProps(['currentSpu'])
const spuInfo = ref(props.currentSpu)

const attrInfoList = ref<attrListModel>([])
const spuImageList = ref<skuImageListModel>([])
const spuSaleAttrList = ref<spuSaleAttrListModel>([])

const skuInfo = reactive<skuInfoModel>({
  spuId: props.currentSpu.id,
  category3Id: 0, // 设置一个默认值
  skuName: '',
  price: 0,
  weight: 0,
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [],
  skuDefaultImg: '',
})

onMounted(() => {
  getAttrInfoList()
  getSpuSaleAttrList()
  getSpuImageList()
})
const categoryStore = useCategoryStore()
const getAttrInfoList = async () => {
  const { cate1Id, cate2Id, cate3Id } = categoryStore
  attrInfoList.value = await reqGetAttrInfoList(cate1Id as number, cate2Id as number, cate3Id as number)
}
const getSpuSaleAttrList = async () => {
  spuSaleAttrList.value = await reqGetSpuSaleAttrList(props.currentSpu.id)
}
const getSpuImageList = async () => {
  const imgList = await reqGetSpuImageList(props.currentSpu.id)
  // 请求回来的图片数据需要加工一下：添加 isDefault 属性
  spuImageList.value = imgList.map(item => ({ ...item, isDefault: '0' }))
}

watch(skuInfo, (v) => {
  console.log(v)
}, { deep: true, immediate: true })

// 处理选中 or 全选
const handleSelect = (selection: skuImageListModel) => {
  skuInfo.skuImageList = selection

  skuInfo.skuImageList.forEach((item: skuImageModel, index: number) => {
    item.spuImgId = selection[index].id
  })
  // skuInfo.skuImageList = selection.map(item => {
  //   return {
  //     id: item.id,
  //     imgName: item.imgName,
  //     imgUrl: item.imgUrl,
  //     isDefault: item.isDefault,
  //     spuImgId: item.id
  //   }
  // })
}
// 全选
const handleSelectAll = (selection: skuImageListModel) => {
  // console.log(selection)
}
// 设置默认图片
const handleSetDefault = (row: skuImageModel) => {
  // 排他：先让所有项的 isDefault 改为'0'
  spuImageList.value.forEach((item: skuImageModel) => item.isDefault = '0')
  row.isDefault = '1'

  // 设置默认图片
  skuInfo.skuDefaultImg = row.imgUrl
}
// 提交保存
const emit = defineEmits(['changeTab'])
const handleSave = async () => {

  // 加工数据
  skuInfo.category3Id = categoryStore.cate3Id as number

  skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map((item: skuAttrValueModel) => {
    const [attrId, valueId] = (item as string).split(':')
    return {
      attrId: Number(attrId),
      valueId: Number(valueId)
    }
  })

  // 过滤掉值为 undefined 的值
  skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map((item: skuSaleAttrValueModel) => ({ saleAttrValueId: Number(item) }))

  await reqSaveSkuInfo(skuInfo)
  // 添加成功后，跳转到 SpuList 
  emit('changeTab', 1)
}
</script>

<style lang="scss" scoped>
img {
  max-width: 100px;
}
</style>